package com.ald.crossex.service;

import com.ald.crossex.dao.CeCoreUserDao;
import com.ald.crossex.dto.AppUserDto;
import com.ald.crossex.dto.BaseResponse;
import com.ald.crossex.dto.JqGridRequest;
import com.ald.crossex.dto.SysUserDto;
import com.ald.crossex.entity.TCeCoreUser;
import com.ald.crossex.util.ErrorCode;
import com.ald.crossex.util.JqGridFilterUtils;
import com.ald.crossex.util.Page;
import com.ald.crossex.util.SecurityUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by lishijiong on 15/1/21.
 */
@Service
public class UserService {


    @Autowired
    private HibernateTemplate hibernateTemplate;
    @Autowired
    private CeCoreUserDao userDao;


    private Logger logger = Logger.getLogger(UserService.class);

    /**
     * 新增用户
     *
     * @param user
     * @return
     */
    @Transactional
    public void addUser(TCeCoreUser user) {


//        String password = user.getPassword();
//        user.setPassword(SecurityUtil.encode(password,SecurityUtil.MD5));
        user.setPassword("123456");
        user.setUpdateTime(new Date());
        user.setCreateTime(new Date());
        user.setIsDelete(0);
        user.setOrgId(1);
        userDao.create(user);
    }

    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @Transactional
    public void updateUser(TCeCoreUser user) {

        TCeCoreUser u = userDao.query(user.getUid());
        u.setUsername(user.getUsername());
        u.setEmail(user.getEmail());
        u.setPhone(user.getPhone());
        u.setNickname(user.getNickname());
        u.setType(user.getType());
        u.setUpdateTime(new Date());
        userDao.update(u);
    }

    /**
     * 删除用户
     *
     * @param uid
     * @return
     */
    @Transactional
    public int delUser(String uid) throws Exception {
        try {
            String[] ids = uid.split(",");
            int i;
            for (i=0; i < ids.length; i++) {
                hibernateTemplate.bulkUpdate("update TCeCoreUser set isDelete = 1 where uid = ?", new Object[]{Integer.parseInt(ids[i])});
            }
            return i;
        } catch (DataAccessException e) {
            logger.error("删除用户:" + uid + "失败!", e);
            throw new Exception("删除用户:" + uid + "失败!");
        }

    }

    /**
     * 根据账号密码查询用户信息
     *
     * @param username
     * @param password
     * @return
     */
    public TCeCoreUser getTCeCoreUserByUsernameAndPassword(String username, String password) {

//        password = SecurityUtil.encode(password, SecurityUtil.MD5);
        List<TCeCoreUser> users = userDao.queryByHql("from TCeCoreUser where username = ? and password = ? and isDelete <> 1", new Object[]{username, password});
        return users.size() > 0 ? users.get(0) : null;
    }

    /**
     * 系统用户列表
     *
     * @return
     */
    public Page listSysUser(JqGridRequest request) {
        Page page = new Page(request.getPage(), request.getRows());

        String conditionSql = " where 1=1 and isDelete <> 1 and type = 0 ";

        if (StringUtils.isNotEmpty(request.getFilters())) {
            conditionSql += JqGridFilterUtils.convertJqGridFilter2String(request.getoFilters());
        }

        String orderSql = " order by " + (StringUtils.isEmpty(request.getSidx()) ? "uid" : request.getSidx()) + " " + request.getSord();

        List<TCeCoreUser> users = userDao.queryPageByHQL("select count(*) from TCeCoreUser " + conditionSql, "from TCeCoreUser " + conditionSql + orderSql, new Object[]{}, page);

        List<SysUserDto> userDtos = new ArrayList<SysUserDto>();
        for (TCeCoreUser u : users) {
            SysUserDto dto = new SysUserDto();

            BeanUtils.copyProperties(u, dto);
            userDtos.add(dto);
        }
        page.setDatas(userDtos);
        return page;
    }

    /**
     * 应用用户列表
     *
     * @return
     */
    public Page listAppUser(JqGridRequest request) {

        Page page = new Page(request.getPage(), request.getRows());

        String conditionSql = " where 1=1 and isDelete <> 1 and ( type = 1 or type = 2 )";

        if (StringUtils.isNotEmpty(request.getFilters())) {
            conditionSql += JqGridFilterUtils.convertJqGridFilter2String(request.getoFilters());
        }

        String orderSql = " order by " + (StringUtils.isEmpty(request.getSidx()) ? "uid" : request.getSidx()) + " " + request.getSord();

        List<TCeCoreUser> users = userDao.queryPageByHQL("select count(*) from TCeCoreUser " + conditionSql, "from TCeCoreUser " + conditionSql + orderSql, new Object[]{}, page);

        List<AppUserDto> userDtos = new ArrayList<AppUserDto>();
        for (TCeCoreUser u : users) {
            AppUserDto dto = new AppUserDto();

            BeanUtils.copyProperties(u, dto);
            userDtos.add(dto);
        }
        page.setDatas(userDtos);
        return page;
    }

    /**
     * 根据微信wid获取用户信息
     *
     * @param wid
     * @return
     */
    public TCeCoreUser getUserByWechatId(Integer wid) {
        List<TCeCoreUser> users = userDao.queryByHql("from TCeCoreUser where wid = ? and isDelete = 0 ", new Object[]{wid});
        if (users.size() < 0) {
            return null;
        } else {
            return users.get(0);
        }
    }

}
